package com.iwunu.gateway.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.cache.RedisService;
import com.iwunu.gateway.constant.ApartmentConstant;
import com.iwunu.gateway.constant.ResultCodeEnum;
import com.iwunu.gateway.entity.FLockUser;
import com.iwunu.gateway.entity.OrgUser;
import com.iwunu.gateway.repository.OrgUserRepository;
import com.iwunu.gateway.service.FlockOrgService;
import com.iwunu.gateway.service.FlockUserService;
import com.iwunu.gateway.service.JpaService;
import com.iwunu.gateway.service.OrgLoginService;
import com.iwunu.gateway.service.TokenService;
import com.iwunu.gateway.util.ResultUtil;
import com.iwunu.gateway.util.VerifyPhoneUtil;
import com.iwunu.gateway.util.WechatDecryptDataUtil;
import com.iwunu.gateway.vo.LoginBindPhoneVo;
import com.iwunu.gateway.vo.LoginParamVo;
import com.iwunu.gateway.vo.SendSmsVo;
import com.iwunu.gateway.vo.TokenVo;
import com.iwunu.gateway.vo.UserInfoVo;
import com.iwunu.iot.common.util.DataUtil;
import com.iwunu.iot.common.util.DateUtil;
import com.iwunu.iot.common.util.Result;
import com.iwunu.iot.common.util.StringUtil;
import com.iwunu.iot.common.wechat.OpenIdUtil;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author kinfeng
 * @date 2019/6/13 11:35 AM
 * @description
 */
@Service
public class OrgLoginServiceImpl implements OrgLoginService {

    @Autowired
    private TokenService tokenService;
    @Resource
    private JpaService jpaService;
    @Resource
    private FlockOrgService flockOrgService;  

    public Result login(String phone, String password) throws Exception {
    	String pwd = new SimpleHash("SHA-1", phone,password).toString();	//密码加密
        OrgUser org = flockOrgService.findOrgUser(phone,pwd);
        if(org == null){
        	return ResultUtil.generateResult(ResultCodeEnum.INVALID_PARAMS_ORG.getCode(),ResultCodeEnum.INVALID_PARAMS_ORG.getDesc()); 
        }
        TokenVo tokenVo = tokenService.getToken(org.getUserId().toString());
        org.setOrganization(tokenVo.getToken());
        jpaService.update(org);
        return ResultUtil.generateResult(ResultCodeEnum.OK.getCode(),ResultCodeEnum.OK.getDesc(),JSON.parseObject(tokenVo.toString()));

    }

    @Override
    public Result refreshToken(String authorization) {
        //重新生成token
        TokenVo tokenVo = tokenService.reshToken(authorization);
        return ResultUtil.generateResult(ResultCodeEnum.OK.getCode(),ResultCodeEnum.OK.getDesc(),JSON.parseObject(tokenVo.toString()));
    }

}
